'use strict';
// 营业员首页控制器
import {
    viewInit,
    showSignSuccess,
    showDialog,
    hideListDialong,
    hideErroDialog,
    showErroDialog,
    showMerQrCode,
    hideMerQrCode,
    showErroDialog2,
    hideErroDialog2
} from '../views/staffHomeView.js';

import {} from '../base/observer.js';
import {
    getConfig
} from '../components/wxConfig.js';
import {
    Logout
} from '../components/logout.js';

var wc = require("../components/winLocation.js")
var latitude, longitude;
var token, loginName, openid, loginType, mer_no, mer_name;
var logoutObject;
var touchInfoSubmit = false;
$(document).on("pageinit", "#staffHome_page", controllerInit);

// 初始化控制器
function controllerInit() {
    wc.checkBrowser();
    initValue();
    viewInit();
    hasRegister();
    initOnEvent();
    getLocation();
}


// 请求是否注册接口
function hasRegister() {
    //    var zcsever = wlprotocol + baseurl + "IsSignServlet";
    var parameters = {};
    parameters.token = token;
    parameters.loginName = loginName;
    parameters.openid = openid;
    parameters.loginType = loginType;
    wc.postAjax(zcsever, parameters, registerBack);

}


// 注册成功回调函数
function registerBack(rdata) {
    console.dir(rdata);
    if (rdata.login_response) {
        haslogin(rdata);
        return;
    }

    if (rdata.sign_response && rdata.sign_response.resp_code == "01") { // 已开户 未签到
        $.publish("registerEnd");
        acctQueryMyMoney();
        //        location.href = "./lodin.html" + location.search;
    } else if (rdata.sign_response && rdata.sign_response.resp_code == "02") { // 已开户 已签到
        $.publish("registerEnd");
        showSignSuccess();
        acctQueryMyMoney();

    } else if (rdata.sign_response && rdata.sign_response.resp_code == "03") { // 未开户未签到
        $("#user_name").val(rdata.sign_response.cust_name);
        showDialog();
        //       acctQueryMyMoney(); 
    } else if (rdata.sign_response && rdata.sign_response.resp_code == "04") { //未开户 已签到
        $("#user_name").val(rdata.sign_response.cust_name);
        showDialog();
        showSignSuccess();
        //        acctQueryMyMoney();
    }
}



// 点击每个商户名后的二维小图标 取ticket
function bindMerchanListClick() {
    $("#merchanList").on("click", function(e) {
        console.dir(e);
        if ($(e.target).attr("data-mer_no")) {
            mer_no = $(e.target).attr("data-mer_no");
            mer_name = $(e.target).find(".weui-cell__bd p").text();
        } else {
            mer_no = $(e.target).parents("[data-mer_no]").attr("data-mer_no");
            mer_name = $(e.target).parents("[data-mer_no]").find(".weui-cell__bd p").text();
        }

        sessionStorage.setItem("mer_no", mer_no);
        // 取生成二维码用的 tl_mer_no
        if (mer_no) {
            hideListDialong();
            //var servletUrl = window.location.protocol + baseurl + "MerQrCodeServlet";
            $.post(
                servletUrl, {
                    tl_mer_no: mer_no
                },
                merQrCodeCallBack
            );
        } else {
            hideListDialong();
            showErroDialog("该商户没有二维码");
        }

    });
}

// 取得商户二维ticket成功回调生成二维函数
function merQrCodeCallBack(msg) {
    console.dir(msg);
    if (msg.login_response) {
        haslogin(msg);
        return;
    }
    if (msg.lfq_merinfo_response && msg.lfq_merinfo_response.mer_ticket) {
        var tiket = msg.lfq_merinfo_response.mer_ticket;
        $("#merQrCodeDialog img").attr("src", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + tiket);
        $("#qrcode-name").text(mer_name);
        showMerQrCode();

    } else {
        hideListDialong();
        showErroDialog("该商户没有二维码");
    }


}



// 跳转到分期消费页面
function bindFenqiClick(argument) {
    $("#fqxiofei").on("touchstart", function() {
        location.href = OpenIdServlet_URL + "?module=scanPay";
    });
}

// 营业员签到
function qiandaoEvent(latitude, longitude) {

    // 移到urlValue.js
    // var SignServletUrl = wlprotocol + baseurl + "SignServlet";
    var nowTime = (new Date()).getTime();
    $.post(
        SignServletUrl, {
            loginName: loginName,
            token: token,
            openid: openid,
            latitude: latitude,
            longitude: longitude,
            loginType: loginType,
            nowTime: nowTime
        },
        qiandaoCallBack
    );
}

// 签到成功回调函数
function qiandaoCallBack(msg) {
    if (msg.login_response) {
        haslogin(msg);
        return;
    }

    if (msg.sign_response && msg.sign_response.resp_code == "0000") {
        showErroDialog("签到成功");
        showSignSuccess();
    } else {
        if (msg.sign_response && msg.sign_response.resp_code == "0001" && msg.sign_response.res_timestamp) {
            showSignSuccess();
            showErroDialog("8小时内已签到，无需再次签到");
        } else if (msg.sign_response && msg.sign_response.resp_code == "0002") {
            showErroDialog(msg.sign_response.resp_msg, "5秒");
            logoutObject._removeSessionStorage();
            logoutObject.setLocalStorageLogout();
            setTimeout(function() {
                location.href = LoginInit_URL;
            }, 5000);

        } else {
            $qiandao.text("签到");
            showErroDialog("签到失败");
        }


    }

}

// 提示营业员信息
function infoSubmit() {
    console.log("sendclick");
    // var InfoServletUrl = wlprotocol + baseurl + "AddCashierInfoServlet";
    if (touchInfoSubmit || $("#info_submit").hasClass("weui-btn_disabled")) {
        return;
    }else{
      touchInfoSubmit = true;  // 点击过了请求结果还没回来
    }
    
    var parameters = getInfoParameters();
    $.post(
        InfoServletUrl,
        parameters,
        infoSubmitCallBack
    );
}

// 提交营业员信息成功回调函数
function infoSubmitCallBack(data) {
    console.log("infoSubmitCallBack");
    touchInfoSubmit = false;   // 点击过了请求结果回来了,允许点击
    $.publish("registerEnd");
    if (data.login_response) {
        haslogin(data);
        return;
    }

    if (data.recharge_response && data.recharge_response.resp_code == "0000") {

        showErroDialog(data.recharge_response.resp_msg);
        acctQueryMyMoney();
    } else if (data.recharge_response && data.recharge_response.resp_code == "3020") {
        var rmsg = data.recharge_response.resp_msg ? data.recharge_response.resp_msg : "账户绑定成功";
        showErroDialog(rmsg);
    } else if (data.recharge_response && data.recharge_response.resp_msg) {
        showErroDialog2(data.recharge_response.resp_msg);
    } else if (data.error_response && data.error_response.sub_msg) {
        showErroDialog2(data.error_response.msg);
    } else {
        showErroDialog2("开户失败,下次登入开通");
    }



}

// 取第一登入填写的信息
function getInfoParameters() {
    var parameters = {};
    parameters.cust_name = $("#user_name").val();
    parameters.idNo = $("#user_id").val().toUpperCase();
    parameters.cardNo = $("#user_card").val();
    parameters.loginName = loginName;
    parameters.token = token;
    parameters.loginType = loginType;
    parameters.openid = openid;
    parameters.id_no_type = 1;
    return parameters;
}

// 收银员余额查询
function acctQueryMyMoney() {
    var parameters = {
        loginName: loginName,
        token: token,
        loginType: loginType,
        openid: openid
    };

    $.post(TLTD_ACCTQ_URL, parameters, myMoneyBack);

}

// 余额查询回调函数
function myMoneyBack(mdata) {
    console.dir(mdata);
    if (mdata.login_response) {
        haslogin(mdata);
        return;
    }

    if (mdata.acct_response && mdata.acct_response.acct_info_arrays && mdata.acct_response.acct_info_arrays.acct_info[0] && mdata.acct_response.acct_info_arrays && mdata.acct_response.acct_info_arrays.acct_info[0].acct_balance) {
        var infons = mdata.acct_response.acct_info_arrays.acct_info;
        for (var i = 0, l = infons.length; i < l; i++) {
            if (infons[i].acct_type == "3") {
                $("#money").text(mdata.acct_response.acct_info_arrays.acct_info[i].acct_balance);
            }
        }

    } else {
        // 没查到余额
        $("#money").text("暂时查不到余额");
    }
}



// 取商户二维码列表
function getMerQrCodeList() {
    console.log("merclick");
    //    var MerQrListUrl = window.location.protocol + baseurl + "MerQrCodeServlet";
    $.post(
        MerQrListUrl, {
            loginName: loginName,
            token: token,
            loginType: loginType,
            openid: openid
        },
        function(qrcodeList) {
            if (qrcodeList.login_response) {
                haslogin(qrcodeList)
            } else if (qrcodeList.merchant_Qw_response && qrcodeList.merchant_Qw_response.resp_code == "0002") {
                showErroDialog("当前无可交易的商户");
            } else {
                $.publish("showListDialog", [qrcodeList]);
            }
        }

    );
}


// 配置成功获取经纬度
function getLocation() {

    $.subscribe("setConfigEnd", function() {
        wx.ready(function() {
            wx.getLocation({
                type: "gcj02",
                success: function(res) {
                    console.log("getLocation data");
                    console.dir(res);
                    latitude = res.latitude ? res.latitude : "23.34";
                    longitude = res.longitude ? res.longitude : "120.34";
                    qiandaoEvent(latitude, longitude);
                },
                fail: function() {
                    $("#qiandao").text("签到");
                    showErroDialog("获取地理位置失败,请确认是否打开地理位置定位功能并授权微信获得地理位置权限");
                },
                cancel: function(res) {
                    showErroDialog('用户拒绝授权获取地理位置');
                }
            });
        });
    });

}

// 绑定事件
function initOnEvent() {
    $("#erweima").on("click", getMerQrCodeList);
    $("#info_submit").on("touchend", infoSubmit);
    // 绑定签到点击事件
    var $qiandao = $("#qiandao");
    $qiandao.on("touchstart", function() {
        $qiandao.text("正在匹配地址位置...");
        // 先不取经纬度 发qiandaoEvent 到时去掉
        //        qiandaoEvent(latitude, longitude);
        //var get_config_url = wlprotocol +baseurl + 'LFQPlaceServlet';  // 移到 urlValue.js
        getConfig(get_wxconfig_url, {
            "mapUrl": "/tltd/staffHome.html" + location.search
        }, ['openLocation', 'getLocation']);

    });
    bindFenqiClick();
    bindMerchanListClick();
    $("#staff-record").on("touchend", function() {
        setTimeout(function  () {
            location.href = "./staffRecord.html";
        },300);
        
    });
}


// 判断是否有效登入
function haslogin(msg) {
    if (msg.login_response && msg.login_response.resp_code == "1110") {
        showErroDialog("暂无关联商户,请联系商户");
        logoutObject._removeSessionStorage();
        logoutObject.setLocalStorageLogout();
    } else if (msg.login_response) {
        showErroDialog("该账户已在别的地方登录,请重新登入");
    }
    if (msg.login_response) {
        setTimeout(function() {
            location.href = LoginInit_URL;
        }, 3000);
    }

}


// 初始化变量
function initValue() {
    wc.QueryString.Initial();
    //    wlprotocol = window.location.protocol;
    //    baseurl = '//localhost:8080/FuLiBao/';
    window.locationObject = wc.QueryString
    window.getConfig = getConfig;

    getSessionStorage();
    //    setSessionStorage();
    logoutObject = new Logout();
}

// 取本地存储essionStorage
function getSessionStorage() {
    token = sessionStorage.getItem("tltd_token");
    loginName = sessionStorage.getItem("tltd_loginName");
    openid = sessionStorage.getItem("tltd_openid");
    loginType = sessionStorage.getItem("tltd_loginType");
    console.log(token, loginName, openid, loginType);
}


// 设置本地存储SessionStorage
function setSessionStorage() {
    sessionStorage.setItem("tltd_loginName", loginName);
    sessionStorage.setItem("tltd_token", token);
    sessionStorage.setItem("tltd_loginType", loginType);
    sessionStorage.setItem("tltd_openid", openid);
}